package com.yds.developtools.utils

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.*

/**
 * 作者:     YDS
 * 创建时间: 2023/3/29 13:58
 * 页面描述: 计时器
 * tips: YDSCountDownHelper.run(totalSeconds = 10, onStart = {

}, onSecond = {

}, onComplete = {

})
 */
@Suppress("unused")
object YDSCountDownHelper : LifecycleObserver {
    private val mJobList = mutableListOf<Job?>()

//    private var job: Job = Job()
//    private val scope = CoroutineScope(Dispatchers.Default + job)

    /**
     * @param totalSeconds 计时总时长（循环次数）
     * @param isReverse    是否逆序
     * @param delaySeconds 延时时间
     * @param onStart      开始
     * @param onComplete   完成
     * @param onSecond
     */
    fun run(
        totalSeconds: Int = 10,
        isReverse: Boolean = true,
        delaySeconds: Long = 1000,
        onStart: () -> Unit,
        onComplete: () -> Unit,
        onSecond: (num: Int) -> Unit
    ): Job {
        val job = CoroutineScope(Dispatchers.Default).launch {
            var second = if (isReverse) 0 else totalSeconds
            withContext(Dispatchers.Main) {
                onStart()
            }
            repeat(totalSeconds) {
                delay(delaySeconds)
                if (isReverse) second++ else second--
                withContext(Dispatchers.Main) {
                    onSecond(second)
                    if (second == if (isReverse) totalSeconds else 0) {
                        onComplete()
                    }
                }
            }
        }

        mJobList.add(job)
        return job
    }

    /*** 作者: YDS 时间: 2023/3/29 14:31 描述: 取消指定job ***/
    @JvmStatic
    fun onJobCancel(job: Job?) {
        job?.let {
            job.cancel()
            mJobList.remove(job)
        }
    }

    /*** 作者: YDS 时间: 2023/3/29 14:31 描述: 取消全部job【退出app时调用】 ***/
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onJobsCancel() {
        val iterator = mJobList.iterator()
        while (iterator.hasNext()) {
            val job = iterator.next()
            job?.cancel()
            iterator.remove()
        }
    }

}